import 'dart:convert';
import 'dart:io';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:devicelocale/devicelocale.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_plus/flutter_swiper_plus.dart';
import 'package:get/get.dart';
import 'package:namewava/pages/calendar/jc_calendar.dart';
import 'package:namewava/pages/dice/jc_dice.dart';
import 'package:namewava/pages/mine/jc_mine.dart';
import 'package:namewava/utils/jc_cache.dart';
import 'package:namewava/utils/jc_global.dart';
import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:package_info_plus/package_info_plus.dart';

class JcRoot extends StatefulWidget {
  const JcRoot({super.key});

  @override
  State<JcRoot> createState() => _JcRootState();
}

class _JcRootState extends State<JcRoot> {
  RxInt nowIndex = 0.obs;
  List pages = [const JcDice(), const JcCalendar(), const JcMine()];
  final SwiperController _swiperController = SwiperController();
  @override
  void initState() {
    super.initState();
    _someCommentData();
    print(JcScreenutilInfo.screenWidth);
    print(JcScreenutilInfo.statusBarHeight);
  }

  @override
  void dispose() {
    super.dispose();
    _swiperController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          color: const Color(0xFF1445CD),
          child: Swiper(
            loop: false,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              return pages[index];
            },
            itemCount: pages.length,
            controller: _swiperController,
          ),
        ),
        // Obx(() {
        //   Widget widget = nowIndex.value == 0
        //       ? const JcDice()
        //       : nowIndex.value == 1
        //           ? const JcCalendar()
        //           : const JcMine();
        //   return widget;
        // }),
        Positioned(
          child: _bottomWidget(),
          right: 0,
          left: 0,
          bottom: 0,
        )
      ],
    );
  }

  _bottomWidget() {
    var bottomBarHeight = JcScreenutilInfo.bottomBarHeight;
    return Container(
      height: 70 + bottomBarHeight,
      padding: EdgeInsets.only(bottom: bottomBarHeight),
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(JcImagePath.jcTabbarBg), fit: BoxFit.fill)),
      //color: Colors.red,
      width: JcScreenutilInfo.screenWidth,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _tabbarItem(0, JcImagePath.jcTDiceNormal, JcImagePath.jcTDiceSelect),
          _tabbarItem(
              1, JcImagePath.jcTCalendarNormal, JcImagePath.jcTCalendarSelect),
          _tabbarItem(2, JcImagePath.jcTMineNormal, JcImagePath.jcTMineSelect),
        ],
      ),
    );
  }

  _tabbarItem(int index, String normalImage, String selectImage) {
    return Obx(() {
      String image = index == nowIndex.value ? selectImage : normalImage;
      return GestureDetector(
        child: Image.asset(
          image,
          width: 50.w,
          height: 50.w,
        ),
        onTap: () {
          if (index != nowIndex.value) {
            nowIndex.value = index;
            _swiperController.move(index, animation: false);
            String page = index == 0
                ? 'home'
                : index == 1
                    ? 'waveRecorder'
                    : 'mine';
            JcGlobal.of(context).logReport({'page': page});
          }
        },
      );
    });
  }

  _someCommentData() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final currentLocale = await Devicelocale.currentLocale;
    Map<String, dynamic> info = {};
    info['ver'] = packageInfo.version;
    info['p_ver'] = packageInfo.buildNumber;
    info['pkg'] = packageInfo.packageName;
    info['sys_lan'] = currentLocale;
    info['lang'] = currentLocale;
    info['appName'] = packageInfo.appName;
    DeviceInfoPlugin infoPlugin = DeviceInfoPlugin();
    if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await infoPlugin.iosInfo;
      info['model'] = iosInfo.name;
      const storage = FlutterSecureStorage();
      String? appDeviceId = await storage.read(key: 'appDeviceId');
      if (appDeviceId != null) {
        info['device-id'] = appDeviceId;
      } else {
        info['device-id'] = iosInfo.identifierForVendor;

        ///写入钥匙串
        storage.write(key: 'appDeviceId', value: iosInfo.identifierForVendor);
      }
      info['device-id'] = iosInfo.identifierForVendor;
      info['platform'] = 'iOS';

      ///test.cusmofusion.ios
    } else {
      AndroidDeviceInfo androidInfo = await infoPlugin.androidInfo;
      info['model'] = androidInfo.model;
      info['device-id'] = androidInfo.id;
      info['platform'] = 'Android';
      info['pkg'] = 'test.bigegg.ios';
    }

    JcCache.getInstance().setData('appinfo', jsonEncode(info));
    if (mounted) {
      JcGlobal.of(context).logReport({'page': 'launch'});
    }
    print(info);
  }
}
